package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 获取微信用户信息接口
     */
    public static final String WECHAT_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信登录
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //获取微信小程序的用户id
        String opendId = getOpendId(userLoginDTO);
        if (StringUtils.isBlank(opendId)){
            //抛异常，因为没有拿到openid
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //根据微信返回的openId，判断当期那用户是否是新用户
        //调用mapper擦护心数据库获取用户
        User user = userMapper.getUserByOpenId(opendId);
        //没有在数据库中用openId查询到数据，新用户
        if (user == null){
             user = new User();
             user.setOpenid(opendId);
             user.setCreateTime(LocalDateTime.now());
             //往用户表中新增一条数据，代表注册用户
            userMapper.insert(user);
        }
        //如果查询到了就是老用户
        return user;
    }

    /**
     * 获取微信小程序的用户id
     */
    private String getOpendId(UserLoginDTO userLoginDTO) {
        //1.获取前端传入的授权码
        String code = userLoginDTO.getCode();
        //2.对微信服务器发起请求，请求获取openid
        //构建参数
        HashMap<String, String> params = new HashMap<>();
        params.put("appid",weChatProperties.getAppid());
        params.put("secret",weChatProperties.getSecret());
        params.put("js_code",code);
        params.put("grant_type","authorization_code");
        //使用工具类完成调用
        String userInfoStr = HttpClientUtil. doGet(WECHAT_URL,params);
        JSONObject jsonObject = JSON.parseObject(userInfoStr);
        return jsonObject.getString("openid");
    }
}
